<template>
  <div>
    <!-- 用户名输入框、查询与清空按钮 -->
    <el-form ref="form" label-width="80px" inline>
      <!-- 用户名输入框 -->
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchObj.username"></el-input>
      </el-form-item>
      <!-- 查询与清空按钮 -->
      <el-button type="primary" icon="el-icon-search" @click="searchUsers"
        >查询</el-button
      >
      <el-button @click="clearUsers">清空</el-button>
    </el-form>
    <!-- 添加与删除按钮 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="addUser">添 加</el-button>
      <el-button
        type="danger"
        :disabled="userSelected.length < 1"
        @click="deleteSelected"
        >批量删除</el-button
      >
    </div>
    <!-- table表格
     @selection-change="handleSelectionChange"
     -->
    <el-table
      :data="items"
      ref="multipleTable"
      tooltip-effect="dark"
      style="width: 100%; margin-bottom: 20px"
      border
      v-loading="tableLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" type="index" align="center" width="80">
      </el-table-column>
      <!--用户名  -->
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <!-- 用户昵称 -->
      <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
      <!--  权限列表-->
      <el-table-column prop="roleName" label="权限列表"> </el-table-column>
      <!-- 创建时间 -->
      <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
      <!-- 更新时间 -->
      <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <!-- 分配角色 -->
          <el-button
            title="分配角色"
            type="info"
            size="mini"
            icon="el-icon-user-solid"
            @click="addrole(row)"
          ></el-button>
          <!-- 修改用户 -->
          <el-button
            title="修改用户"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            style="margin-right: 10px"
            @click="updateuser(row)"
          ></el-button>
          <!--删除用户  -->
          <el-popconfirm
            :title="`确定${row.username}删除吗？`"
            @onConfirm="deleteUser(row)"
          >
            <el-button
              title="删除用户"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              slot="reference"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getUserInfo"
    >
    </el-pagination>
    <!-- 添加与修改按钮 弹出框 -->
    <el-dialog
      :title="user.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="form" label-width="80px" :rules="rules" :model="user">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="用户名" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input placeholder="用户昵称" v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!user.id">
          <el-input placeholder="用户密码" v-model="user.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduserconfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 弹出框 -->
    <el-dialog title="设置角色" :visible.sync="dialogVisiblerole" width="width">
      <el-form ref="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="roleuser.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="roleselected"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in roleList"
              :label="role.id"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addrolelist" :loading="addloading"
          >保 存</el-button
        >
        <el-button @click="clearrole">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: 1,
      limit: 3,
      searchObj: {
        username: "",
      },
      checkAll: "",
      total: 0,
      items: [],
      roleList: [],
      roleselected: [],
      roleuser: {},
      tableLoading: true,
      userSelected: [],
      dialogVisible: false,
      dialogVisiblerole: false,
      addloading: false,
      user: {},
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    //获取用户列表
    async getUserInfo(page = 1) {
      this.page = page;
      const { limit, searchObj } = this;
      this.tableLoading = true;
      let result = await this.$API.user.getPageList(page, limit, searchObj);
      if (result.code == 20000) {
        this.tableLoading = false;
        const { total, items } = result.data;
        this.items = items.filter((item) => item.username !== "admin");
        this.total = total - 1;
        this.userSelected = [];
      }
    },
    //每一页展示数改变
    handleSizeChange(limit) {
      this.limit = limit;
      this.getUserInfo();
    },
    //查询用户
    searchUsers() {
      this.getUserInfo();
    },
    //清空查询用户
    clearUsers() {
      this.searchObj.username = "";
      this.getUserInfo();
    },
    //当复选框改变收集id
    handleSelectionChange(userSelected) {
      this.userSelected = userSelected.map((item) => item.id);
    },
    //删除某个用户
    async deleteUser(row) {
      let result = await this.$API.user.removeById(row.id);
      if (result.code == 20000) {
        this.getUserInfo(this.items.length > 1 ? this.page : this.page - 1);
        this.$message({
          type: "success",
          message: "删除成功",
        });
      } else {
        this.$message.error("删除失败");
      }
    },
    //批量删除 弹出框
    deleteSelected() {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        showClose: false,
      })
        .then(async () => {
          let result = await this.$API.user.removeUsers(this.userSelected);
          if (result.code == 20000) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getUserInfo();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch((error) => {
          this.$message("取消删除");
        });
    },
    //添加按钮 展示弹出框
    addUser() {
      this.dialogVisible = true;
      this.user = {};
    },
    //点击确认按钮 添加用户
    adduserconfirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let result = this.user.id
            ? await this.$API.user.update(this.user)
            : await this.$API.user.add(this.user);
          if (result.code == 20000) {
            this.$message({
              type: "success",
              message: this.user.id ? "修改用户成功" : "添加用户成功",
            });
            this.dialogVisible = false;
            this.user.id ? this.getUserInfo(this.page) : this.getUserInfo();
          } else {
            this.$message.error(this.user.id ? "修改用户失败" : "添加用户失败");
          }
        } else {
          this.$message.error(this.user.id ? "修改用户失败" : "添加用户失败");
          return false;
        }
      });
    },
    //修改用户
    updateuser(row) {
      this.user = { ...row };
      this.dialogVisible = true;
    },
    //分配角色
    async addrole(row) {
      this.dialogVisiblerole = true;
      this.roleuser = row;
      let result = await this.$API.user.getRoles(row.id);
      if (result.code == 20000) {
        const { allRolesList, assignRoles } = result.data;
        this.roleList = allRolesList;
        this.roleselected = assignRoles.map((item) => item.id);
      }
    },
    //改变角色复选框
    handleCheckAllChange(value) {
      this.roleselected = value ? this.roleList.map((item) => item.id) : [];
    },
    //勾选某个角色 改变全选
    handleCheckedCitiesChange(value) {
      const { roleList, roleselected } = this;
      this.checkAll = roleList.length === roleselected.length;
    },
    //复选框 取消按钮 清除数据
    clearrole() {
      this.dialogVisiblerole = false;
      this.checkAll = "";
      this.roleList = [];
      this.roleselected = [];
    },
    //添加角色
    async addrolelist() {
      this.addloading = true;
      const userId = this.roleuser.id;
      const roleIds = this.roleselected.join(",");
      const result = await this.$API.user.assignRoles(userId, roleIds);
      if (result.code === 20000) {
        this.addloading = false;
        this.$message({
          type: "success",
          message: "分配角色成功",
        });
        this.clearrole();
        this.getUserInfo(this.page);
      } else {
        this.$message.error("分配角色失败");
      }
    },
  },
};
</script>

<style>
</style>